const WebUser = require("../model/webUser.model");
const { Op } = require("sequelize");
const SNOWFLAKE = require("@zsea/snowflake");
const snowflake = new SNOWFLAKE({
  type: "string",
});

class WebUserService {
  async createUser(username, password, role_type) {
    try {
      const res = await WebUser.create({
        web_id: snowflake.nextId(),
        username: username,
        pwd: password,
        role_type: role_type,
      });
      if (res.dataValues) {
        delete res.dataValues.pwd;
        return {
          code: "10000",
          message: "注册成功",
          data: res.dataValues,
        };
      }
    } catch (error) {}
  }
  // 校验用户是否存在
  async checkWebUserDoesExsit(username) {
    const findOption = {};
    try {
      if (username) {
        Object.assign(findOption, { username });
      }
      const res = await WebUser.findOne({
        raw: true,
        where: findOption,
      });
      return res ? res : null;
    } catch (error) {
      console.log(error);
    }
  }
  // 检查用户登录
  async checkWebUserLogin(username, pwd) {
    const findOption = {};
    try {
      if (username) {
        Object.assign(findOption, { username });
      }
      const res = await WebUser.findOne({
        raw: true,
        where: findOption,
      });
      // console.log("用户信息", res);
      delete res.pwd;
      return res;
    } catch (error) {
      console.log(error);
    }
  }

  // 获取用户列表
  async getWebUserList(pageNum, pageSize, username) {
    const offset = (pageNum - 1) * pageSize;
    const findOption = {};
    try {
      if (username) {
        // 模糊查询

        Object.assign(findOption, {
          username: {
            [Op.like]: `%${username}%`,
          },
        });

        const total = await WebUser.count({
          where: findOption,
        });
        const res = await WebUser.findAll({
          limit: pageSize * 1,
          offset,
          where: findOption,
        });
        return {
          pageNum,
          pageSize,
          total,
          list: res,
        };
      } else {
        const total = await WebUser.count({
          where: findOption,
        });
        const res = await WebUser.findAll({
          limit: pageSize * 1,
          offset,
          where: findOption,
        });
        return {
          pageNum,
          pageSize,
          total,
          list: res,
        };
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 删除用户
  async deleteUser(web_id) {
    try {
      const res = await WebUser.destroy({
        where: {
          web_id,
        },
      });
      return res;
    } catch (error) {
      console.log(error);
    }
  }
}

module.exports = new WebUserService();
